local hx__lanyue = fk.CreateSkill {
  name = "hx__lanyue",
}

local U = require "packages/utility/utility"

hx__lanyue:addEffect(fk.AfterCardsMove, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(hx__lanyue.name) then return end
    if event == fk.AfterCardsMove and player:usedSkillTimes(hx__lanyue.name, Player.HistoryRound) < 1 then
      local cards = {}
      local room = player.room
      for _, move in ipairs(data) do
        if move.moveReason == fk.ReasonDiscard and move.toArea == Card.DiscardPile then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip and room:getCardArea(info.cardId) == Card.DiscardPile then
              table.insertIfNeed(cards, info.cardId)
            end
          end
        end
      end
      cards = player.room.logic:moveCardsHoldingAreaCheck(cards)
      if #cards > 0 then
        event:setCostData(self, cards)
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local num = #event:getCostData(self)
    room:addPlayerMark(player, "@@hx__lanyue_effect")
    local tos = table.filter(room:getAlivePlayers(), function(p) return p:getMark("@hx__lanyue") > 0 end)
    if #tos > 0 then
      local n = tos[1]:getMark("@hx__lanyue")
      room:removePlayerMark(tos[1], "@hx__lanyue", n)
      room:removePlayerMark(tos[1], MarkEnum.MinusMaxCards, n)
    end
    local choices = {"#hx__lanyue-get"}
    if #room.discard_pile > 0 then
      table.insert(choices, "#hx__lanyue-find")
      if #room.discard_pile < num then
        num = #room.discard_pile
      end
    end
    local choice = room:askToChoice(player, {
      choices = choices,
      skill_name = hx__lanyue.name,
    })
    if choice == "#hx__lanyue-get" then
      room:moveCardTo(event:getCostData(self), Card.PlayerHand, player, fk.ReasonJustMove, hx__lanyue.name, nil, true, player)
    elseif choice == "#hx__lanyue-find" then
      local ids = room:getCardsFromPileByRule(".|.|.", num, "discardPile")
      if #ids > 0 then
        room:moveCards({
          ids = ids,
          to = player,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonJustMove,
          proposer = player,
          skillName = hx__lanyue.name,
        })
      end
    end
    local turn_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Turn)
		if turn_event == nil then return end
		local to = turn_event.data.who
    room:addPlayerMark(to, "@hx__lanyue", num)
    room:addPlayerMark(to, MarkEnum.MinusMaxCards, num)
  end,
})

return hx__lanyue